//
//  AppDelegate.swift
//  moofun_ipad
//
//  Created by ZX on 2017/9/6.
//  Copyright © 2017年 ZX. All rights reserved.
//

import UIKit
import AVFoundation
import AudioToolbox

let ORANGECOLOR = UIColor.init(red: 1, green: 152/255.0, blue: 1/255.0, alpha: 1)


let IPHONE_8:Int32 = 80000
//信鸽 key
/// ACCESS ID
let kXinGeAppId: UInt32 = 2200175007//填写ACCESS ID,例如:1234567890

/// ACCESS KEY
let kXinGeAppKey:String! = "IPHH3R825F4D"//填写ACCESS KEY,例如:"AB345F7H89012"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UITabBarControllerDelegate ,UIActionSheetDelegate {

    var window: UIWindow?
    var alert: UIAlertController?
    var player: AVPlayer?
    var navWaitingOrders : UINavigationController!


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //信鸽注册
        
        if #available(iOS 10.0, *) {
            let center = UNMutableNotificationContent.current()
            center.delegate = self
            center.requestAuthorization(options: [.alert,.badge,.sound]) { (granted, error) in
                if granted {
                    center.getNotificationSettings(completionHandler: { (settings) in
                        print(settings)
                    })
                } else {
                    print("失败")
                }
            }
        } else {
            // Fallback on earlier versions
            if #available(iOS 8.0, *) {
                let seetings = UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil)
                application.registerUserNotificationSettings(seetings)
            } else {
                // Fallback on earlier versions
                application.registerForRemoteNotifications(matching: [.alert,.badge,.sound])
            }
        }
        

        
        XGPush.startApp(kXinGeAppId, appKey: kXinGeAppKey)
        XGPush.initForReregister { () -> Void in
            if !XGPush.isUnRegisterStatus(){
                if __IPHONE_OS_VERSION_MAX_ALLOWED >= IPHONE_8{
                   
                    self.registerPush()
                }else{
                    //iOS8之前注册push方法
                    //注册Push服务，注册后才能收到推送3
                    self.registerPush()
                }
            }
        }
        
        XGPush.handleLaunching(launchOptions, successCallback: {
            print("success")
        }) {
            print("error")
        }

        
        return true
    }
    private func registerAppNotificationSettings(launchOptions: [NSObject: AnyObject]?) {
       
    }
    
   
    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        
    }
    
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("didFailToRegisterForRemoteNotifications error:\(error.localizedDescription)\n\n")
    }
    
    /**
     收到通知的回调
     
     @param application  UIApplication 实例
     @param userInfo 推送时指定的参数
     */
    
    private func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
    {
        print("[XGDemo] userinfo %@", userInfo)
        //消息在userinfo["aps"]
        //弹窗
        // 清空通知栏通知
        UIApplication.shared.cancelAllLocalNotifications()
        UIApplication.shared.applicationIconBadgeNumber = 0
        
    }
    /**
     收到静默推送的回调
     
     @param application  UIApplication 实例
     @param userInfo 推送时指定的参数
     @param completionHandler 完成回调
     */
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("[XGDemo] receive slient Notification")
        print("[XGDemo] userinfo %@", userInfo)
//        XGPush.handleReceiveNotification(userInfo, successCallback: {
//            print("[XGDemo] Handle receive success")
//        }) {
//            print("[XGDemo] Handle receive error")
//        }
        completionHandler(UIBackgroundFetchResult.newData)
    }
    func registerPushForIOS8()
    {
        //Types
        if #available(iOS 8.0, *) {
            
            
            //Actions
//            let acceptAction = UIMutableUserNotificationAction()
//            
//            acceptAction.identifier = "ACCEPT_IDENTIFIER"
//            acceptAction.title      = "Accept"
            
//            acceptAction.activationMode = UIUserNotificationActivationMode.foreground
            
//            acceptAction.isDestructive = false
//            acceptAction.isAuthenticationRequired = false
//            
            
            //Categories
//            let inviteCategory = UNNotificationCategory()
//            inviteCategory.identifier = "INVITE_CATEGORY";
//            
//            inviteCategory.setActions([acceptAction], for: UIUserNotificationActionContext.default)
//            inviteCategory.setActions([acceptAction], for: UIUserNotificationActionContext.minimal)
//            
//            let categories = NSSet(objects: inviteCategory)
            
//            let mySettings:UNNotificationSettings = UNNotificationActionx
            
//            let mySettings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: categories as? Set<UIUserNotificationCategory>)
            
//            UIApplication.shared.registerUserNotificationSettings(mySettings)
            
        } else {
            // Fallback on earlier versions
        }
        
    }
    
    func registerPush(){
        //
        UIApplication.shared.registerForRemoteNotifications(matching: [.sound, .badge, .alert])
//        UIApplication.shared .registerForRemoteNotifications();
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

